package com.greendragon.service.frontend.impl; 

import com.greendragon.persistence.constant.ExceptionCode;
import com.greendragon.persistence.dao.IUserDao;
import com.greendragon.persistence.domain.User;
import com.greendragon.service.frontend.IUserFrontendService;
import com.greendragon.util.EncryptionUtil;

/** 
 * @author wulibin, exceptsky@gmail.com, 2011-9-24 下午10:38:00
 * 
 */
public class UserFrontendService extends BaseFrontendService<User> implements IUserFrontendService{
private IUserDao userDao;
	
	@Override
	public void add(User user) {
		String PwMd5 = EncryptionUtil.encodeMD5(user.getPassword());
		user.setPassword(PwMd5);
		dao.add(user);
	}

	@Override
	public User updatePassword(User user, String oldPw, String newPw)
			throws Exception {
		String oldPwMd5 = EncryptionUtil.encodeMD5(oldPw);
		String newPwMd5 = EncryptionUtil.encodeMD5(newPw);
		if(user.getPassword().equals(oldPwMd5)){
			user.setPassword(newPwMd5);
			userDao.update(user);
			return user;
		}else{
			throw new Exception(ExceptionCode.NEWPASSWORD_NOT_EQUAL_OLDPASSWORD);
		}
	}

	@Override
	public User getByName(String name) {
		return userDao.getByName(name);
	}

	@Override
	public String getSecurityAnswer(long uid) {
		return get(uid).getSecurityAnswer();
	}

	@Override
	public String getSecurityQuestion(long uid) {
		return get(uid).getSecurityQuestion();
	}

	@Override
	public User login(String name, String pw) {
		User user = getByName(name);
		if(null != user){
			String PwMd5 = EncryptionUtil.encodeMD5(pw);
			if(PwMd5.equals(user.getPassword())){
				return user;
			}else{
				return null;
			}
		}else{
			return null;
		}
	}
	
	@Override
	public void update(User user){
		dao.update(user);
	}

	@Override
	public void register(User user) {
		add(user);
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
		setDao(userDao);
	}
	
}
 